package org.bdware.doip.endpoint.doipClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.bdware.doip.core.codec.packet.PacketNettyTCPCodec;
import org.bdware.doip.core.utils.GlobalConfigurations;

import java.net.URI;
import java.net.URISyntaxException;

public class NettyDoipTCPClientChannel extends NettyDoipClientChannel {

    final Bootstrap b = new Bootstrap();
    EventLoopGroup group;

    public NettyDoipTCPClientChannel() {
    }

    @Override
    public void close() {
        if(handler != null) handler.close();
        isConnected = false;
    }

    @Override
    public void connect(String targetUrl) throws URISyntaxException {
        URI uri = new URI(targetUrl);
        logger.debug("[URI Parse]scheme:" + uri.getScheme() + "  host: " + uri.getHost() + "  port: " + uri.getPort());
        if(group == null){
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
            group = new NioEventLoopGroup();
            b.group(group);
            handler = new NettyDoipClientHandler();
            b.channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(
                            new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel ch) {
                                    ChannelPipeline p = ch.pipeline();
                                    p.addLast(new LengthFieldBasedFrameDecoder(GlobalConfigurations.tcpFrameLength,20,4,0,0))
                                            .addLast(new PacketNettyTCPCodec())
                                            .addLast(handler);
                                }
                            });
            logger.info("[DoipClient] Create TCP Client!");
        }
        try {
            logger.debug("[URI Parse]host: "+ uri.getHost() + "  port: " + uri.getPort());
            channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
            handler.setChannel(channel);
        }catch (Exception e){
            e.printStackTrace();
        }
        isConnected = true;
    }

}
